/* eslint-disable object-shorthand */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable import/no-extraneous-dependencies */

// 页面容器
import { PageContainer } from "@ant-design/pro-layout";

import React, {
  PureComponent, createRef, createContext, useContext
} from "react";

import {
  Table, Button, message, Select, Form, Input, Modal, DatePicker, Space
} from "antd";
import { connect } from "dva";
import { PlusOutlined } from "@ant-design/icons";
import { findIndex } from "lodash";
import moment from "moment";
import { createNewData, listTableData } from "@/services/material.js";
import { history } from "umi"; // 页面跳转

const { Option } = Select;

class MaterialManage extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      total: 0,
      currentPage: 1,
      size: 10,
      dataSource: [],
      query: 0,
      isReady: false,
      confirmData: [],
      createNewFormVisible: false
    };

    // 定义表格的列结构
    this.tableColumns = [
      {
        title: "id",
        dataIndex: "key",
        key: "key",
        width: 50,
        render: (text, record, index) => {
          const { currentPage } = this.state;
          return (currentPage - 1) * 10 + index + 1;
        }
      },
      {
        title: "原料名称",
        dataIndex: "mat_name",
        key: "mat_name",
        width: 200
      },
      {
        title: "原料品牌",
        dataIndex: "mat_brand",
        key: "mat_brand",
      },
      {
        title: "包装规格",
        // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径，dataIndex: ["pack_spec", "type"]会显示pack_spec.type字段
        dataIndex: "pack_spec",
        key: "pack_spec",
        width: 200,
        // 控制列数据的显示方式，可以将复合字段的子项按照自己想要的方式组装
        render: (text, record, index) => `${record.pack_spec.type}/${record.pack_spec.value}${record.pack_spec.unit}`
      },
      {
        title: "包装单价",
        dataIndex: "pack_price",
        key: "pack_price",
        width: 100,
        sorter: (a, b) => a.pack_price - b.pack_price // 指定该列是否支持排序以及排序算法
      },
      {
        title: "起购量",
        dataIndex: "min_purchase",
        key: "min_purchase",
        width: 100,
        sorter: (a, b) => a.min_purchase - b.min_purchase // 指定该列是否支持排序以及排序算法
      },
      // {
      //   title: "客户标签",
      //   key: "tags",
      //   dataIndex: "tags",
      //   render: (tags) => (
      //     <>
      //       {tags.map((tag) => {
      //         let color = tag.length > 5 ? "geekblue" : "green";
      //         if (tag === "loser") {
      //           color = "volcano";
      //         }
      //         return (
      //           <Tag color={color} key={tag}>
      //             {tag.toUpperCase()}
      //           </Tag>
      //         );
      //       })}
      //     </>
      //   )
      // },
      {
        title: "操作",
        key: "action",
        width: 200,
        render: (text, record, index) => (
          <Space size="middle">
            <a onClick={() => this.editRecord(record)}>编辑</a>
            <a onClick={() => this.deleteRecord(record)}>删除</a>
          </Space>
        )
      }
    ];

    this.searchFormRef = createRef();
    this.tenantFormRef = createRef();
    this.tableWrapperRef = createRef();
    this.otherHeight = 0;
  }

  // 页面加载时触发获取数据
  componentDidMount() {
    this.fetchTableData().finally(() => this.setState({ isReady: true }));
  }

  createNew = () => {
    history.push("/matMgt/createNewMat");
  };

  // 获取表格数据
  fetchTableData = async () => {
    // 页码，请求记录数
    const { size, currentPage } = this.state;
    // 搜索条件
    const { name } = this.getSearchFormValue();

    // 获取数据
    const {
      data: { ret },
      data: {
        data: { list, total, query }
      }
    } = await listTableData({ size, page: currentPage, name: name });

    if (ret !== 0) {
      return;
    }
    this.setState({ total, dataSource: list, query });
  };

  // 翻页
  handlePageChange = (page, size) => {
    this.setState({ currentPage: page, size }, this.fetchTableData);
  };

  // 新建记录
  createRecord = () => {
    this.setState({
      createNewFormVisible: true
    });
  };

  changeTenantStatus = (id) => {
    // todo
  };

  // 删除记录
  deleteRecord = (record) => {
    alert(`正在删除的记录id为：${record.key}`);
  };

  // 批量删除记录
  batchDelRecord = () => {
    alert("batch delete records");
  };

  editRecord = (record) => {
    history.push(`/matMgt/editMat/?id=${record.key}`);
  };

  resetFliter = () => {
    // todo
  };

  search = () => {
    this.fetchTableData();
  };

  getSearchFormValue = () => {
    const { getFieldsValue } = this.searchFormRef.current;
    const { name } = getFieldsValue();
    return { name };
  };

  getModalFormValue = () => {
    const { getFieldsValue } = this.tenantFormRef.current;
    const {
      name, deadTime, rights, numbers
    } = getFieldsValue();
    return {
      name,
      deadTime,
      rights,
      numbers
    };
  };

  // 新建或编辑后的保存处理
  saveRecord = (type) => {
    const {
      name, deadTime, rights, numbers
    } = this.getModalFormValue();
    if (type === "new") {
      // 调用service服务创建数据
      createNewData({
        name: name,
        deadTime: deadTime.unix(),
        rights: rights,
        numbers: numbers
      }).then((tenantRes) => {
        if (tenantRes.data.ret === 0) {
          message.success("创建成功！");
          this.setState({
            createNewFormVisible: false
          });
        } else {
          message.success("创建失败");
        }
      });
    }
  };

  /** Form弹窗示例：简单的弹窗表单，字段平铺，样式已按照UI定制 */
  /**
  renderFormModal = () => {
    const { createNewFormVisible } = this.state;
    const selectAfterDateUnit = (
      <Select defaultValue="月" className="select-after">
        <Option value="月">月</Option>
        <Option value="周">周</Option>
        <Option value="天">天</Option>
      </Select>
    );

    return (
      <Modal
        centered
        title="新建记录"
        visible={createNewFormVisible}
        onOk={() => this.saveRecord()}
        onCancel={() => this.setState({ createNewFormVisible: false })}
      >
        <Form ref={this.tenantFormRef}>
          <Form.Item
            name="name"
            label="客户名称："
            rules={[{ required: true, message: "请输入客户名称" }]}
          >
            <Input placeholder="请输入" />
          </Form.Item>

          <Form.Item
            name="age"
            label="客户年龄："
            rules={[{ required: true, message: "请输入客户年龄" }]}
          >
            <Input addonAfter={selectAfterDateUnit} placeholder="请输入月数" />
          </Form.Item>

          <Form.Item
            name="address"
            label="客户地址"
            rules={[{ required: true, message: "请选择到期日期" }]}
          >
            <DatePicker placeholder="请选择" />
          </Form.Item>

          <Form.Item
            name="tags"
            label="客户标签"
            rules={[{ required: true, message: "请选择租户等级" }]}
          >
            <Select
              // showSearch
              placeholder="请选择"
            >
              {this.renderRightsOptions()}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  */

  // 原料弹窗表单：复杂的分区表单
  renderFormModal = () => {
    const { createNewFormVisible } = this.state;
    const selectAfterDateUnit = (
      <Select defaultValue="月" className="select-after">
        <Option value="月">月</Option>
        <Option value="周">周</Option>
        <Option value="天">天</Option>
      </Select>
    );

    return (
      <Modal
        centered
        title="新建原料"
        className="fullPageModal"
        visible={createNewFormVisible}
        onOk={() => this.saveRecord()}
        onCancel={() => this.setState({ createNewFormVisible: false })}
      >
        <div className="tableCard">
          <div className="tableCardToolbar">
            <div className="toolbarTitle">基础信息</div>
            <div className="toolbarButtons">
              <Button type="default">折叠</Button>
            </div>
          </div>

          <div className="tableCardTable">
            <Form ref={this.tenantFormRef} layout="inline">
              <Form.Item
                name="name"
                label="客户名称："
                rules={[{ required: true, message: "请输入客户名称" }]}
              >
                <Input placeholder="请输入" />
              </Form.Item>

              <Form.Item
                name="age"
                label="客户年龄："
                rules={[{ required: true, message: "请输入客户年龄" }]}
              >
                <Input addonAfter={selectAfterDateUnit} placeholder="请输入月数" />
              </Form.Item>

              <Form.Item
                name="address"
                label="客户地址"
                rules={[{ required: true, message: "请选择到期日期" }]}
              >
                <DatePicker placeholder="请选择" />
              </Form.Item>
            </Form>
          </div>
        </div>
      </Modal>
    );
  };

  render() {
    const {
      total, dataSource, currentPage, isReady, size, query
    } = this.state;

    return (
      /**
       * 最外层的容器必须是PageContaine
       * - title不用管，自动根据routers.ts里面的name出现在页面
       * - 设置footer属性可以出现页面底部的toolbar（fix bottom风格）
       */
      <PageContainer>
        {/* 页面header区域：搜索栏 区域 */}
        <div className="pagehead-searchbar">
          {/* 搜索栏是一个多个field组成的form，每个field有label和搜索框，搜索框根据field类型书写对应的input类型 */}
          <Form
            layout="inline" // 从左到右排布搜索field
            ref={this.searchFormRef} // 设置搜索form的ref，从而获取搜索Form的内容
          >
            {/* 这里书写可以搜索的field，书写filed对应的input类型 */}
            <Form.Item name="mat_name" label="原料名称">
              <Input placeholder="请输入关键字" />
            </Form.Item>

            <Form.Item name="mat_brand" label="原料品牌">
              <Input placeholder="请输入关键字" />
            </Form.Item>

            <Form.Item name="mat_brand" label="原料品牌">
              <Input placeholder="请输入关键字" />
            </Form.Item>

            <Form.Item name="mat_brand" label="原料品牌">
              <Input placeholder="请输入关键字" />
            </Form.Item>

            <Form.Item name="mat_brand" label="原料品牌">
              <Input placeholder="请输入关键字" />
            </Form.Item>

            <Form.Item>
              <Button type="default">重置</Button>
              <Button type="primary">提交</Button>
            </Form.Item>
          </Form>
        </div>

        <div className="ourCard">
          <div className="header">
            <div className="title">表格标题</div>
            <div className="toolbtn">
              <Button
                type="primary"
                onClick={() => {
                  this.createNew();
                }}
              >
                新建原料
              </Button>
              <Button type="default">批量删除</Button>
            </div>
          </div>

          <div className="content">
            <Table
              columns={this.tableColumns} // 表格的列定义
              dataSource={dataSource} // 装载获取的数据到表格内
              loading={!isReady} // 获取数据时的页面转轮
              rowSelection={{ type: "checkbox" }} // 行首的选择框方式
              pagination={{ position: ["bottomRight"], defaultCurrent: 1, total: total }} // 分页器的样式
            />
          </div>
        </div>
        {/* 新建，编辑等缺省不可见的表单 */ this.renderFormModal()}
      </PageContainer>
    );
  }
}

export default MaterialManage;
